<?php 
// +----------------------------------------------------------------------
// | ThinkPHP                                                             
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://thinkphp.cn All rights reserved.      
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>                                  
// +----------------------------------------------------------------------
// $Id$

class PublicAction extends Action {

    function _initialize() 
    {
       if(!isset($_SESSION[C('USER_AUTH_KEY')]) && MODULE_NAME!="Public") {
			$this->redirect(__APP__."/Public/login");
        }
    }


	public function checkLogin() {
		$User	=	D('Admin');
		if(empty($_POST['username'])) {
			$this->error('帐号错误！');
		}elseif (empty($_POST['password'])){
			$this->error('密码必须！');
		}elseif ($_SESSION['verify'] != md5($_POST['verify'])){
			$this->error('验证码错误！');
		}
        //生成认证条件
        $map            =   array();
        $map["username"]	=	$_POST['username'];
	
		$authInfo = $User->find($map);
        //使用用户名、密码和状态的方式进行认证
        if(false === $authInfo) {
            $this->error('用户名不存在或已禁用！');
        }else {
			if($authInfo['username']	!=  $_POST['username']) {
				$this->error('帐号错误！');
			}
            if($authInfo['password'] != md5($_POST['password'])) {
            	$this->error('密码错误！');
            }
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
             $_SESSION["username"]	=	$authInfo['username'];
			$this->success('登录成功！');
		}
	}

	public function login() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->display();
		}else{
			$this->redirect('index','Index');
		}
	}

    public function logout() 
    {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION[C('USER_AUTH_KEY')]);
            $this->assign("message",'登出成功！');
            $this->assign("jumpUrl",__URL__.'/login/');
        }else {
            $this->assign('error', '已经登出！');
        }
        $this->forward();
    }

    /**
     +----------------------------------------------------------
     * 验证码显示
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    function verify() 
    {
        import("ORG.Util.Image");
        if(isset($_REQUEST['adv'])) {
        	Image::showAdvVerify(); 
        }else {
        	Image::buildImageVerify(); 
        }
    }
    /**
     +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作 
     * 可以在action控制器中重载
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    function getReturnUrl() 
    {
		if(Session::is_set("IndexUrl"))
			return Session::get("IndexUrl");
		else{
			$module=defined('C_MODULE_NAME')?C_MODULE_NAME:MODULE_NAME;
			return __URL__.'?'.C('VAR_MODULE').'='.$module.'&'.C('VAR_ACTION').'='.C('DEFAULT_ACTION');
		}
    }

	 /**
     +----------------------------------------------------------
     * 取得当前操作的model
     +----------------------------------------------------------
     * @access pravite 
     +----------------------------------------------------------
     * @return Model object
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */

	 protected function getModel()
	{	
		 //当前操作名
		$actionName=strtolower(ACTION_NAME);
		//或者在重载属性modelName中定义
		 if(isset($this->modelName)){
		 if(is_array($this->modelName)){
			//是否定义了操作模型
			if(isset($this->modelName[$actionName])) 
				$modelName=$this->modelName[$actionName];
			else
				$modelName=$this->name;
		 }
		 else
			 $modelName=$this->modelName;
		 }
		 else
			 $modelName=$this->name;
		if(!$model=D($modelName))
			throw_exception("模型不存在".$modelName);  
		return $model;
	}
	 /**
     +----------------------------------------------------------
     * 首页列出所有项目 
     * 可以在action控制器中重载
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
	public function index()
    {	
		//保存首页参数，方便跳转
		Session::set("IndexUrl",$_SERVER['REQUEST_URI']);
		$model= $this->getModel();
        $where = $this->_search();
        if(!empty($model)) {
        	$this->_list($model,$where);
        }
		$this->display();
        return;
    }
    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected 
     +----------------------------------------------------------
     * @param string $name 数据对象名称 
     +----------------------------------------------------------
     * @return HashMap
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function _search() 
    {
        return "";
    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected 
     +----------------------------------------------------------
     * @param Model $model 数据对象 
     * @param HashMap $map 过滤条件 
     * @param string $sortBy 排序 
     * @param boolean $asc 是否正序 
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _list($model,$map,$sortBy='',$asc=true) 
    {	
        //排序字段 默认为主键名
        if(isset($_REQUEST['order'])) {
            $order = $_REQUEST['order'];
        }else {
            $order = !empty($sortBy)? $sortBy: $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if(isset($_REQUEST['sorts'])) {
            $sort = $_REQUEST['sorts']?'asc':'desc';
        }else {
            $sort = $asc?'asc':'desc';
        }
        //取得满足条件的记录数
	    $count = $model->count();
		if($count>0) {
			import("ORG.Util.Page");
			//创建分页对象
			if(!empty($_REQUEST['listRows'])) {
				$listRows  =  $_REQUEST['listRows'];
			}else {
				$listRows  =  20;
			}
			$p  = new Page($count,$listRows,__APP__."/".MODULE_NAME."/".ACTION_NAME);

			$voList     = $model->where($map)->order($order.' '.$sort)->limit($p->firstRow.','.$p->listRows)->findAll();

			//分页显示
			$page       = $p->show();
			//列表排序显示
			$sortImg    = $sort ;                                   //排序图标
			$sortAlt    = $sort == 'desc'?'升序排列':'倒序排列';    //排序提示
			$sort       = $sort == 'desc'? 1:0;                     //排序方式
			//模板赋值显示
			$this->assign('list',       $voList);
			$this->assign('sort',       $sort);
			$this->assign('order',      $order);
			$this->assign('sortImg',    $sortImg);
			$this->assign('sortType',   $sortAlt);
			$this->assign("page",       $page);
		}
        return ;
    }

   public function insert() 
    {
		$model	=$this->getModel();
        if(false === $model->create()) {
        	$this->error($model->getError());
        }

        //保存当前数据对象
        $id = $model->add();
        if($id) { //保存成功
            //成功提示
			 $this->assign("jumpUrl",$this->getReturnUrl());
            $this->success(L('_INSERT_SUCCESS_'));
        }else { 
            //失败提示
            $this->error(L('_INSERT_FAIL_'));
        }
    }

	public function add() 
    {
		$this->display();
	}

	function edit()
    {
		$model	=$this->getModel();
		$id     = $_REQUEST['id'];
		$vo	    = $model->find($id);
		$this->assign('vo',$vo);
		$this->display();
	}

	function update() 
    {
        
		$model	=$this->getModel();
        if(false === $model->create()) {
        	$this->error($model->getError());
        }

        //保存当前数据对象
        $id = $model->save();
        if($id) { //保存成功
            //成功提示
			 $this->assign("jumpUrl",$this->getReturnUrl());
            $this->success("修改成功!");
        }else { 
            //失败提示
            $this->error('修改失败!');
        }
	}

    /**
     +----------------------------------------------------------
     * 默认删除操作
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    public function delete()
    {
       $model	=$this->getModel();
        $where = $model->getPk().' IN ('.$_REQUEST['id'].')';
        if($model->delete(array("where"=>$where))){
            $this->assign("message",'删除成功！');
            $this->assign("jumpUrl",$this->getReturnUrl());
        }else {
            $this->assign('error',  '删除失败！');
        }
        $this->forward();
    }

    /**
     +----------------------------------------------------------
     * 默认禁用操作
     * 
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    public function forbid()
    {
		$model	=$this->getModel();
        $where = $model->getPk().' IN ('.$_GET['id'].')';
        $update = array('status'=>0);
        if($model->save($update,array("where"=>$where))){
            $this->assign("message",'状态禁用成功！');
            $this->assign("jumpUrl",$this->getReturnUrl());
        }else {
            $this->assign('error',  '状态禁用失败！');
        }
        $this->forward();
    }

    /**
     +----------------------------------------------------------
     * 默认恢复操作
     * 
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    public function resume()
    {
        //恢复指定记录
		 $model	=$this->getModel();
        $condition = $model->getPk().' IN ('.$_GET['id'].')'; 
		$map=array("status"=>1);
        if($model->save($map,array("where"=>$condition))){
            $this->assign("message",'状态恢复成功！');
            $this->assign("jumpUrl",$this->getReturnUrl());
        }else {
            $this->assign('error',  '状态恢复失败！');
        }
        $this->forward();
    }

	 /**
     +----------------------------------------------------------
     * 默认保存排序
     * 
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */

	 public function orders()
	{
		//检查参数
		if(!is_array($_POST["orders"])){
			$this->error("参数错误!");
			return false;
		}
		$model=$this->getModel();
		$error="";
        $pk = $model->getPk();
		//保存排序
		foreach($_POST["orders"] as $id => $order){
			$model->{$pk}=$id;
			$model->orders=$order;
			if(!$model->save())
				$error.=$model->getError();
		}
		if($error)
			$this->error("更新排序出错!".$error);
		else
			$this->success("更新排序成功!");
	}

}
?>